package com.example.computer_exam_training_sys.controller;

import com.example.computer_exam_training_sys.entity.UserAnalysisInfo;
import com.example.computer_exam_training_sys.service.UserAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/useranalysis")
@CrossOrigin
public class UserAnalysisController {

    @Autowired
    private UserAnalysisService service;

    //http://localhost:8080/useranalysis/all
    @GetMapping("/all")
    public List<UserAnalysisInfo> findAll() {
        return service.findAll();
    }

    //http://localhost:8080/useranalysis/findbyuserid?userId=1
    @GetMapping("/findbyuserid")
    public List<UserAnalysisInfo> findByUserId(@RequestParam Integer userId) {
        return service.findByUserId(userId);
    }

    //http://localhost:8080/useranalysis/findbyid?id=3
    @GetMapping("/findbyid")
    public UserAnalysisInfo findById(@RequestParam Integer id) {
        return service.findById(id);
    }

    //http://localhost:8080/useranalysis/insert
    //{
    //  "userId": 1,
    //  "courseId": 101,
    //  "practiceRangeStart": "2024-01-01",
    //  "practiceRangeEnd": "2024-02-01",
    //  "totalQuestions": 200,
    //  "correctQuestions": 160,
    //  "accuracyRate": 0.8,
    //  "weakPoints": "{\"chapter1\": \"logic\", \"chapter3\": \"recursion\"}",
    //  "studyTrend": "{\"2024-01\": 60, \"2024-02\": 80}"
    //}
    @PostMapping("/insert")
    public int insert(@RequestBody UserAnalysisInfo info) {
        return service.insert(info);
    }

    //http://localhost:8080/useranalysis/update
    //{
    //  "id": 3,
    //  "userId": 1,
    //  "courseId": 101,
    //  "practiceRangeStart": "2024-01-01",
    //  "practiceRangeEnd": "2024-02-01",
    //  "totalQuestions": 250,
    //  "correctQuestions": 200,
    //  "accuracyRate": 0.8,
    //  "weakPoints": "{\"chapter1\": \"logic\"}",
    //  "studyTrend": "{\"2024-01\": 100, \"2024-02\": 150}"
    //}
    @PostMapping("/update")
    public int update(@RequestBody UserAnalysisInfo info) {
        return service.update(info);
    }

    //http://localhost:8080/useranalysis/delete?id=3
    @DeleteMapping("/delete")
    public int deleteById(@RequestParam Integer id) {
        return service.deleteById(id);
    }
    
    //http://localhost:8080/useranalysis/generate?userId=1&courseId=1&startDate=2024-01-01&endDate=2024-02-01
    @GetMapping("/generate")
    public UserAnalysisInfo generateAnalysis(
            @RequestParam Integer userId,
            @RequestParam Integer courseId,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        return service.generateUserAnalysis(userId, courseId, startDate, endDate);
    }
    
    //http://localhost:8080/useranalysis/auto-analyze?userId=1&courseId=1
    //或者不提供courseId分析所有课程: http://localhost:8080/useranalysis/auto-analyze?userId=1
    @GetMapping("/auto-analyze")
    public Map<String, Object> autoAnalyze(
            @RequestParam Integer userId,
            @RequestParam(required = false) Integer courseId) {
        
        Map<String, Object> response = new HashMap<>();
        
        // 如果提供了courseId，则只分析指定课程
        if (courseId != null) {
            int result = service.saveOrUpdateUserAnalysis(userId, courseId);
            
            if (result > 0) {
                response.put("success", true);
                response.put("message", "指定课程分析数据已生成");
                
                // 获取最新的分析数据
                List<UserAnalysisInfo> analyses = service.findByUserId(userId).stream()
                    .filter(a -> a.getCourseId().equals(courseId))
                    .collect(Collectors.toList());
                
                if (!analyses.isEmpty()) {
                    response.put("data", analyses.get(0));
                }
            } else {
                response.put("success", false);
                response.put("message", "分析数据生成失败");
            }
        } 
        // 如果没有提供courseId，则分析用户所有课程的总体数据
        else {
            Map<String, Object> overallAnalysis = service.getUserOverallAnalysis(userId);
            
            if ((int)overallAnalysis.get("courseCount") > 0) {
                response.put("success", true);
                response.put("message", "所有课程总体分析数据已生成");
                response.put("totalQuestions", overallAnalysis.get("totalQuestions"));
                response.put("totalCorrectQuestions", overallAnalysis.get("totalCorrectQuestions"));
                response.put("averageAccuracyRate", overallAnalysis.get("averageAccuracyRate"));
                response.put("courseCount", overallAnalysis.get("courseCount"));
                
                // 获取并添加所有课程的薄弱知识点组合
                String combinedWeakPoints = service.getCombinedWeakPoints(userId);
                response.put("weakPoints", combinedWeakPoints);
            } else {
                response.put("success", false);
                response.put("message", "未找到用户课程数据或分析失败");
            }
        }
        
        return response;
    }
    
    //http://localhost:8080/useranalysis/update-analysis?id=3&userId=1&courseId=1&startDate=2024-01-01&endDate=2024-02-01
    @PostMapping("/update-analysis")
    public Map<String, Object> updateAnalysis(
            @RequestParam Integer id,
            @RequestParam Integer userId,
            @RequestParam Integer courseId,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        
        Map<String, Object> response = new HashMap<>();
        
        // 生成新的分析数据
        UserAnalysisInfo newAnalysis = service.generateUserAnalysis(userId, courseId, startDate, endDate);
        
        // 设置ID以便更新现有记录
        newAnalysis.setId(id);
        
        // 更新记录
        int result = service.update(newAnalysis);
        
        if (result > 0) {
            response.put("success", true);
            response.put("message", "分析数据已更新");
            response.put("data", newAnalysis);
        } else {
            response.put("success", false);
            response.put("message", "分析数据更新失败");
        }
        
        return response;
    }
    
    //http://localhost:8080/useranalysis/refresh-analysis?id=3
    @PostMapping("/refresh-analysis")
    public Map<String, Object> refreshAnalysis(@RequestParam Integer id) {
        Map<String, Object> response = new HashMap<>();
        
        // 使用服务层的刷新方法
        int result = service.refreshAnalysis(id);
        
        if (result > 0) {
            response.put("success", true);
            response.put("message", "分析数据已刷新");
            // 获取更新后的数据
            UserAnalysisInfo updatedAnalysis = service.findById(id);
            response.put("data", updatedAnalysis);
        } else {
            response.put("success", false);
            response.put("message", "分析数据刷新失败或记录不存在");
        }
        
        return response;
    }
    
    //http://localhost:8080/useranalysis/overall-analysis?userId=1
    @GetMapping("/overall-analysis")
    public Map<String, Object> getOverallAnalysis(@RequestParam Integer userId) {
        Map<String, Object> response = new HashMap<>();
        
        Map<String, Object> overallAnalysis = service.getUserOverallAnalysis(userId);
        
        if ((int)overallAnalysis.get("courseCount") > 0) {
            response.put("success", true);
            response.put("message", "所有课程总体分析数据已生成");
            response.put("data", overallAnalysis);
            
            // 获取并添加所有课程的薄弱知识点组合
            String combinedWeakPoints = service.getCombinedWeakPoints(userId);
            response.put("weakPoints", combinedWeakPoints);
        } else {
            response.put("success", false);
            response.put("message", "未找到用户课程数据或分析失败");
        }
        
        return response;
    }
}
